package jp.co.systemi.asp.workflow.group;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import jp.co.systemi.asp.workflow.Main;
import jp.co.systemi.asp.workflow.annotation.FormInput;
import jp.co.systemi.asp.workflow.data.Group;
import jp.co.systemi.asp.workflow.data.GroupMeta;
import jp.co.systemi.asp.workflow.data.UserGroupMeta;
import jp.co.systemi.asp.workflow.peer.GroupPeer;

import org.apache.wicket.PageParameters;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.image.Image;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.PropertyModel;
import org.slim3.datastore.Datastore;
import org.slim3.datastore.GlobalTransaction;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class GroupSearch extends Main {
    private static final Logger log = Logger.getLogger(GroupSearch.class
            .getName());
    final GroupSearch thisPage = this;
    final private Group model = new Group();

    List<Group> groups = new ArrayList<Group>();
    @FormInput
    public TextField<String> groupName = new TextField<String>("wi_groupName",
            new PropertyModel<String>(model, "name"));
    @FormInput
    public TextField<String> parentGroup = new TextField<String>(
            "wi_parentGroup", new PropertyModel<String>(model, "parentGroup"));

    public GroupSearch() {
        Form<Group> form = new MainForm<Group>(this, "wi_groupSearchForm") {
            private static final long serialVersionUID = 1L;

            @Override
            protected void onSubmitInner() {
                groups.clear();
                groups.addAll(GroupPeer.doSearch(model));
            }
        };
        final WebMarkupContainer tblGroups = new WebMarkupContainer(
                "wi_tblGroups");
        tblGroups.setOutputMarkupId(true);
        ListView<Group> listview = new ListView<Group>("wi_trGroup", groups) {
            /**
             *
             */
            private static final long serialVersionUID = -3654822552366070627L;

            protected void populateItem(ListItem<Group> item) {
                UserService userService = UserServiceFactory.getUserService();
                final Group group = (Group) item.getModelObject();
                PageParameters pars = new PageParameters();
                log.info("code = " + group.getCode());
                pars.add("code", group.getCode());
                BookmarkablePageLink<GroupRef> link = new BookmarkablePageLink<GroupRef>(
                        "wi_tdGroupLink", GroupRef.class, pars);

                link.add(new Label("wi_tdGroupName", new PropertyModel<String>(
                        group, "name")));
                item.add(link);

                // 親組織
                pars = new PageParameters();
                pars.add("code", group.getParentGroup());
                link = new BookmarkablePageLink<GroupRef>(
                        "wi_tdParentGroupLink", GroupRef.class, pars);
                GroupMeta gm = GroupMeta.get();
                Group parentGroup = Datastore.query(gm).filter(
                        gm.code.equal(group.getParentGroup())).asSingle();
                if (parentGroup != null) {
                    group.setParentGroupName(parentGroup.getName());
                }
                log.info("親グループ名：　" + group.getParentGroupName());
                link.add(new Label("wi_tdParentGroupName",
                        new PropertyModel<String>(group, "parentGroupName")));
                item.add(link);
                AjaxLink<Object> wi_delete = new AjaxLink<Object>("wi_tdDelete") {
                    private static final long serialVersionUID = -8430876475452070427L;

                    @Override
                    public void onClick(AjaxRequestTarget target) {
                        log.info("to delete group : " + group.getCode()
                                + " id = " + group.getId());
                        GlobalTransaction gtx = Datastore
                                .beginGlobalTransaction();
                        List<Key> keys = new ArrayList<Key>();
                        keys.add(group.getId());
                        // ユーザグループを削除
                        UserGroupMeta ugm = UserGroupMeta.get();
                        List<Key> userGroupKeys = Datastore.query(ugm).filter(
                                ugm.groupCode.equal(group.getCode()))
                                .asKeyList();
                        keys.addAll(userGroupKeys);
                        gtx.delete(keys);
                        keys.clear();
                        // 下位組織を更新
                        GroupMeta gm = GroupMeta.get();
                        List<Group> children = Datastore.query(gm).filter(
                                gm.parentGroup.equal(group.getCode())).asList();
                        for (Group child : children) {
                            child.setParentGroup(null);
                            keys.add(child.getId());
                        }
                        gtx.put(keys);
                        gtx.commit();

                        // ユニックキーも削除
                        Datastore.deleteUniqueValue(GroupReg.UNIQUE_CODE, group.getCode());
                        Datastore.deleteUniqueValue(GroupReg.UNIQUE_NAME, group.getName());
                        // 検索結果も更新
                        groups.remove(group);
                        for (Group g : groups) {
                            if (group.getCode().equals(g.getParentGroup())) {
                                g.setParentGroup(null);
                                g.setParentGroupName(null);
                            }
                        }
                        target.addComponent(tblGroups);
                    }
                };
                wi_delete.setEnabled(userService.isUserAdmin());
                Image image = new Image("wi_deleteImg");
                if(userService.isUserAdmin()){
                    image.add(new SimpleAttributeModifier("src", "/images/delete_icon.jpg"));
                }
                else{
                    image.add(new SimpleAttributeModifier("src", "/images/disable_delete_icon.jpg"));
                }
                wi_delete.add(image);

                item.add(wi_delete);
            }
        };
        form.add(tblGroups);
        tblGroups.add(listview);
    }
}
